﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace ActionModel.Utility
{
	public class JsonSerializer
	{
		public static string ToJSON(object obj)
		{
			System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
			string json = jss.Serialize(obj);

			//string json = ToJsJson(obj);

			string ccx = "\"" + @"\\/Date\((\d{1,})\)\\/" + "\"";
			return Regex.Replace(json, ccx, "new Date($1)");
		}

		public static T FromJSON<T>(string input)
		{
			System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();

			string ccx = @"new Date\((\d{1,})\)";
			input = Regex.Replace(input, ccx, "\"" + @"\\/Date($1)\\/" + "\"");
			return jss.Deserialize<T>(input);
		}

		///// <summary>
		///// Json序列化,用于发送到客户端
		///// </summary>
		//public static string ToJsJson(object item)
		//{
		//    DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());

		//    using (MemoryStream ms = new MemoryStream())
		//    {
		//        serializer.WriteObject(ms, item);
		//        StringBuilder sb = new StringBuilder();
		//        sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
		//        return sb.ToString();
		//    }
		//}

		///// <summary>
		///// Json反序列化,用于接收客户端Json后生成对应的对象
		///// </summary>
		//public static T FromJsonTo<T>(string jsonString)
		//{

		//    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

		//    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

		//    T jsonObject = (T)ser.ReadObject(ms);

		//    ms.Close();

		//    return jsonObject;

		//}
	}
}
